#!/usr/bin/env R
# -*- coding: utf-8  -*-
#
# This script is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Izaskun Mallona
# izaskun.mallona@gmail.com
#
# Inspired on
# http://www.oga-lab.net/RGM2/func.php?rd_id=stats:dendrapply


# In this example we employ a cor matrix rather than 
# classically computed distances to cluster; fit the
# starting dataframe according to your needs.


rawdata = read.csv(file="data_foo.csv")
data=rawdata[,2:13]
rownames(data)=rawdata[,1]
cormatrix = cor(data)

# performing the hclust
hc <- hclust(as.dist(1-cor(data)))

# saving the hclust as a dendrogram
dhc <- as.dendrogram(hc)

# creating a dictionary of the colors
# it must be like
# colorCodes = list("AL081"="red", "BL061"="blue") and so on
#
# TODO
# colorCodes = list() TODO

# this will return a vector with all the labels
# sorted like depicted at the tree when reading
# the leaves from left to right
 
orderedLabels <- hc$label[hc$order[1:length(hc$label)]]

# this will look at the dictionary created in colorCodes 
# and will create a vector of the colors applied to the
# dendrogram

labellingColors <-vector()
for (i in 1: length(orderedLabels)){
    labellingColors = c(labellingColors, as.character(colorCodes[orderedLabels[i]]))
}

# this is for printing
require(graphics)

# attribute extraction
dendrapply(dhc, function(n) utils::str(attributes(n)))

# coloring labels function
local({
  colLab <<- function(n) {
      if(is.leaf(n)) {
        a <- attributes(n)
        i <<- i+1
        attr(n, "nodePar") <-
            # lab.font = 3 stands for italics
            c(a$nodePar, list(lab.col = mycols[i], lab.font= 2))
      }
      n
  }
  
  # mycols is the vector which contains the colors
  mycols <- labellingColors
  i <- 0
 })
 
# applying the function above to the dendrogram
dL <- dendrapply(dhc, colLab)
plot(dL)
